# DIRTY
import marker
import pygame

class WorldRenderer (object):
    """ Render a world"""
    def __init__(self, world, system):
        self.world = world
        self.system = system
        self.screen = self.system.screen
        self.grid = self.world.getGrid()
        
    #   was: fps, fps_max, fps_avg, fps_avg_c = 0, fps_avg_val=0
    def render_world (self):
        # Render all layers of world items onto system screen surface
        
        # Draw backgound
        self.screen.blit (self.world.background, self.grid.tOriginPi)
            
        # z-buffer related :
        #if self.DEBUG:
        #    for t in self.grid.tiles:
        #        #t.draw(self.screen, self.grid, self.font[8])    
        #        if self.village in self.grid.getObjectsByTag (t):
        #            pygame.draw.circle(self.screen, (255,0,0), t.rPosPi.center, 2)
        for h in xrange (0, self.grid.HTi):
            for obj in self.world.grid.zbuffer.get_zbuffer_for_depth(h):
                obj.draw(self.screen, self.grid)
        
#        fps = self.timer.get_fps()
#        if fps> fps_max: fps_max = fps
#        fps_avg[fps_avg_c] = fps
#        fps_avg_c += 1
#        if fps_avg_c > 99:
#            fps_avg_c = fps_avg_val = 0
#            for i in fps_avg:
#                fps_avg_val += i
#            fps_avg_val /= 100.0 

#        self.screen.blit (self.font[18].render("FPS: " + str(int(fps)), False, (255,255,255)), (10,10))
#        self.screen.blit (self.font[18].render("MAX: " + str(int(fps_max)), False, (255,255,255)), (10,30))
#        self.screen.blit (self.font[18].render("AVG: " + str(int(fps_avg_val)), False, (255,255,255)), (10,50))
#        self.timer.tick()

        # Render additional layers
        
        # Display a map if we have one
        try:
            s, p = self.world.get_render_layer ("map")
            self.screen.blit (s, self.grid.tOriginPi)
        except:
            pass

        try:
            s, p = self.world.get_render_layer ("minimap")
            self.screen.blit (s, (600,0))
        except:
            pass
        
        

         # GUI
#        self.info.displayVillageInfo (self.village)
#        if self.info.isVillageInfoShown():
#            self.screen.blit (self.font[14].render( "Ein kleines Dorf", False, (0,0,0)), (630,40))
#            self.screen.blit (self.font[14].render( "Essen: "+str(self.village.getFood()), False, (0,0,0)), (630,55))
#            self.screen.blit (self.font[14].render( "Bewohner: "+str(len(self.village.getResidents())), False, (0,0,0)), (630,75))
        
        # Draw rectangle for selection
        marker.drawMarkingArea(self.screen)
        
        #pygame.display.update()
        pygame.display.flip()    

class World_AI (object):
    """ Calculate AI behavor in the world"""
     
    def __init__ (self, world):
        self.world = world
            
    def main_calculate_ai (self):
        # Instead of updating every skeleton every frame (for s in skeleton), 
        # I just update 1 skeleton per frame 
        s = self.skeleton[self.skelCount]
    
        # State machine for skeletons    
        curState = s.getState()
        enemy = None
        # is a enemy near?
        for m in self.man:
            if m.collideCircle (s):
                enemy = m
                break
        
        # first: transition rules
        if curState == "walk":
            if enemy != None:
                s.setState ("attack", "attack", enemy)
            else:
                if s.reachedDestination (self.grid):
                    rx = helper.rndint (self.grid.WTi)
                    ry = helper.rndint (self.grid.HTi)
                    s.setState ("walk", "walk", self.grid.getTileAtTi ((rx,ry)))
        elif curState == "attack":
            if enemy == None:
                rx = helper.rndint (self.grid.WTi)
                ry = helper.rndint (self.grid.HTi)
                s.setState ("walk", "walk", self.grid.getTileAtTi ((rx,ry)))
            else:
                s.attack (enemy)
        
        # berechne heading und position des ziels
        curState = s.getState()
        if curState == "attack" or curState == "walk":
            target = s.followPath(self.grid)
            if target != None:
                tile = self.grid.getTileAtPi (s.tPosPi)
                #self.grid.unregister (tile, s)
                s.moveForward(s.speed)
                s.setZDepth(self.grid.getTileAtPi(target).getZDepth())
                #self.grid.register (self.grid.getTileAtPi(target), s)      
    
            
            
        
            
        self.skelCount += 1
        if self.skelCount > len(self.skeleton)-1: self.skelCount=0
    
       
        
    
    
        # State machine for man
        m = self.man[self.manCount]
        curState = m.getState()
        food = m.getHomeVillage().getFood()
        
        
        # first: transition rules
        if curState != "harvest" and food <= 10: 
            m.setState ("harvest", "walk", m.getHomeVillage())
        elif curState == "harvest" and food > 10: 
            m.setState ("gohome", "walk")
        
        # second handle states, what to do
        curState = m.getState()
        
        if curState == "run" or curState == "walk" or curState == "gohome":
            target = m.followPath(self.grid)
            if target != None:
                m.moveForward(m.speed)
                m.setZDepth(self.grid.getTileAtPi(target).getZDepth())      
            elif m.reachedDestination (self.grid):
                #FIXME hack: spezialbehandlung, weil wir das z-buffer handling des maennchens
                # nicht korrekt haben: der zbuffer des maennchen haengt noch an tPosPi, nicht wie
                #bei hausern an einem definierten punkt (-> siehe drawvon human.py und dem /2 trick)
                m.setZDepth(self.grid.getTileAtPi(vSub(m.tPosPi,(40,40))).getZDepth())
                # endhack
                m.setState("idle", "idle")
        if curState == "harvest":
            target = m.followPath(self.grid)
            if target != None:
                m.moveForward(m.speed)
                m.setZDepth(self.grid.getTileAtPi(target).getZDepth())      
            elif m.reachedDestination (self.grid):
                m.state.setActiveSet ("harvest")
                m.harvest()
                
        # Consume food
        #m.consumeFood()
                
        self.manCount += 1
        if self.manCount > len(self.man)-1: self.manCount=0
